package com.mitake.utils;

import java.io.ByteArrayOutputStream;
import java.io.FileInputStream;
import java.io.IOException;

import org.json.JSONArray;
import org.json.JSONObject;

public class Util {
	
	public static boolean DEBUG = false;
	
	public static final String CONTENT_TYPE = "text/html; charset=UTF-8";
	
	public static boolean hasDifference(String s1, String s2)
	{
		if(s1 != null && s2 != null && s1.equals(s2))
		{
			return false;
		}
		
		return true;
	}
	
	
	public static long getRunInterval(String rootPath) throws IOException
	{
		String filename = rootPath + "/setting/conf.ini";
		
		FileInputStream fis = new FileInputStream(filename);
		ByteArrayOutputStream baos = new ByteArrayOutputStream();
		
		byte[] b = new byte[1024];
		int len;
		
		while((len = fis.read(b, 0, 1024)) > -1)
		{
			baos.write(b, 0, len);
		}
		
		fis.close();
		
		String data = new String(baos.toByteArray(), "utf-8");
		
		JSONObject root = new JSONObject(data);
		return Long.parseLong(root.optString("runInterval", "1000"));
	}
	
	public static String[] getStock(String rootPath) throws IOException
	{
		String filename = rootPath + "/setting/stock.ini";
		
		FileInputStream fis = new FileInputStream(filename);
		ByteArrayOutputStream baos = new ByteArrayOutputStream();
		
		byte[] b = new byte[1024];
		int len;
		
		while((len = fis.read(b, 0, 1024)) > -1)
		{
			baos.write(b, 0, len);
		}
		
		fis.close();
		
		String data = new String(baos.toByteArray(), "utf-8");
		
		JSONArray root = new JSONArray(data);
		
		String[] stock = new String[root.length()];
		/**
		 * 取得主机位置
		 */
		for(int i = 0 ; i < root.length() ; i++)
		{
			JSONObject stockObject = root.optJSONObject(i);

			stock[i] = stockObject.optString("id"); 
		}
		
		return stock;
	}
	
	public static String[][] getHost(String rootPath) throws IOException
	{
		String filename = rootPath + "/setting/cf.ini";
		
		FileInputStream fis = new FileInputStream(filename);
		ByteArrayOutputStream baos = new ByteArrayOutputStream();
		
		byte[] b = new byte[1024];
		int len;
		
		while((len = fis.read(b, 0, 1024)) > -1)
		{
			baos.write(b, 0, len);
		}
		
		fis.close();
		
		String data = new String(baos.toByteArray(), "utf-8");
		
		JSONArray root = new JSONArray(data);

		int hostCount = root.length();
		
		String[][] host = new String[hostCount][4];
		/**
		 * 取得主机位置
		 */
		for(int i = 0 ; i < hostCount ; i++)
		{
			JSONObject hostObject = root.optJSONObject(i);
			
			host[i][0] = hostObject.optString("type"); // 報價型態
			host[i][1] = hostObject.optString("ip"); 
			host[i][2] = hostObject.optString("port");
			host[i][3] = hostObject.optString("desc");
		}
		
		return host;
	}


}
